package com.cxs.shopstore.handler;

import com.cxs.shopstore.es.ESTemplete;
import com.cxs.shopstore.models.Good;
import com.cxs.shopstore.utils.DataCatch;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/*
 * @Author:cxs
 * @Date:2021/5/7  17:32
 * @Version 1.0
 * 京东页面数据解析
 * */
@Slf4j
@Component
public class JsoupHandler {
    @Autowired
    private DataCatch dataCatch;
    @Autowired
    private ESTemplete esTemplete;

    public List<Good> dataHandle(String dataHtml) {
        List<Good> list = new ArrayList<>();
        //使用jsoup解析数据并封装，保存
        Document document = Jsoup.parse(dataHtml);
        //获得商品全文
        Element goodsElement = document.getElementById("J_goodsList");
        //获得商品元素数组
        Elements items = goodsElement.select("ul li.gl-item");
        for (Element item : items) {
            Good good = new Good();
            //获得商品的唯一标识sku
            Long goodSku = Long.parseLong(item.attr("data-sku"));
            //判断该sku是否存在
            if(esTemplete.existBySku(goodSku)){
                log.info("sku为"+goodSku+"商品已存在");
                continue;
            }else{
                good.setGoodSku(goodSku);
                //获得商品标题
                String goodName = item.select("div.p-name").text();
                good.setGoodName(goodName);
                //获得商品价格
                String goodPrice = item.select("div.p-price").text();
                good.setGoodPrice(goodPrice);
                //获得商品卖家
                String goodSaler = item.select("div.p-shop").text();
                good.setGoodSaler(goodSaler);
                //获得商品图片及保存图片
                String imgUrl = "https:" + item.select("div.p-img img").first().attr("data-lazy-img");
                //保存图片并返回图片路径
                imgUrl = imgUrl.replaceAll("n7", "n1");
                String imgPath = dataCatch.saveImgGet(imgUrl);
                good.setGoodImgPath(imgPath);
                //设置入库时间
                good.setGoodCreateTime(Calendar.getInstance().getTimeInMillis());
                list.add(good);
            }
        }
        return list;
    }
}
